﻿using System;
using System.Threading.Tasks;
using log4net;


[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

namespace MyLib
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			var pa = new PlayerActor();


			Console.WriteLine("Hello World!");
			LogHelper.Log("Server", "StartServer");
			var sg = new SaveGame();
			var config = new ServerConfig();
			var am = new ActorManager();

			var lobby = new Lobby();
			am.AddActor(lobby, true);

			var ss = new SocketServer();
			am.AddActor(ss, true);


			Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler);
			RegisterException();

			var port = ServerConfig.instance.configMap["Port"].AsInt;
			ss.Start(port);
			ss.mThread.Join();
			GC.Collect();
			Console.WriteLine("EndServer");
		}

		private static void RegisterException()
		{
			AppDomain.CurrentDomain.UnhandledException += UnhandleExcepition;
			TaskScheduler.UnobservedTaskException += (sender, eventArgs) =>
			{
				eventArgs.SetObserved();
				var error = eventArgs.Exception;
				LogHelper.LogUnhandleException(sender.ToString() + "  " + error.ToString());
			};
		}

		private static void UnhandleExcepition(object sender, UnhandledExceptionEventArgs e)
		{
			var error = e.ExceptionObject as Exception;
			LogHelper.LogUnhandleException(sender.ToString() + "  " + error.ToString());
		}

		private static void myHandler(object sender, ConsoleCancelEventArgs args)
		{
			Debug.Log("ServerStop");
			ActorManager.Instance.Stop();
		}
	}
}
